package com.example.demo.controller;

import com.example.demo.entity.ChargeVO;
import com.example.demo.entity.JsonResultVO;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * Description:
 * <p>@author: LUO</p>
 * Date: 2019-05-16 7:50
 **/
@RestController
@RequestMapping(value = "/ic/test")
public class IcController {

    @Resource
    private UserService userService;

    @RequestMapping(value = "/charge")
    public JsonResultVO icCharge(@RequestBody ChargeVO chargeVO) {
        if(!priceCompare(chargeVO.getCharge())){
            return new JsonResultVO(400,"充值金额需大于0");
        };
        User user = getUser(chargeVO.getIcCode());
        BigDecimal ori = user.getBalance();
        user.setBalance(ori.add(chargeVO.getCharge()));
        this.userService.save(user);
        return new JsonResultVO(200,"充值成功");
    }

    private boolean priceCompare(BigDecimal charge) {
        int r = charge.compareTo(BigDecimal.ZERO);
        return r > 0;
    }

    private User getUser(String icCode) {
        User user = this.userService.getByIcCode(icCode);
        if(user == null){
            user = new User().setIcCode(icCode).setBalance(new BigDecimal(0));
            this.userService.save(user);
        }
        return user;
    }


    @RequestMapping(value = "/query")
    public JsonResultVO icQuery(@RequestBody ChargeVO chargeVO) {
        User user = getUser(chargeVO.getIcCode());
        return new JsonResultVO(user);
    }

    @RequestMapping(value = "/pay")
    public JsonResultVO icPay(@RequestBody ChargeVO chargeVO) {
        if(!priceCompare(chargeVO.getPay())){
            return new JsonResultVO(400,"消费金额需大于0");
        };
        User user = getUser(chargeVO.getIcCode());
        BigDecimal ori = user.getBalance();
        BigDecimal fin = ori.subtract(chargeVO.getPay());
        if(!priceCompare(fin)){
            return new JsonResultVO(400,"消费金额大于余额");
        };

        this.userService.save(user.setBalance(fin));
        return new JsonResultVO(400,"扣费成功");
    }
}
